package by.grsu.pochebut.webpage.car;

import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;

import by.grsu.pochebut.entity.Car;
import by.grsu.pochebut.interf.InterfCar;
import by.grsu.pochebut.webpage.MyPage;

@SuppressWarnings("serial")
public class ListCarPage  extends MyPage {

	@SpringBean
	private InterfCar daoCar;

	public ListCarPage() {
		super();
		// retrieve all objects
		final List<Car> cars = daoCar.findAll();

		// add "list" component and provide list of items which should be
		// rendered
		add(new ListView<Car>("cars", cars) {

			@Override
			protected void populateItem(final ListItem<Car> item) {
				final Car car = item.getModelObject();
				// add "labels" to display each property of the item
				item.add(new Label("model", car.getModel()));
				item.add(new Label("color", car.getColor()));
				item.add(new Label("price", String.valueOf(car.getPrice())));
				item.add(new Label("date", String.valueOf(car.getData())));

				// add link which will forward to the "edit" page
				item.add(new Link<Car>("editlink", new Model<Car>(car)) {
					@Override
					public void onClick() {
						setResponsePage(new EditCarPage(car));
					}
				});

				// add "link" which removes item from database and reload the
				// page
				item.add(new Link<Car>("deletelink", new Model<Car>(car)) {
					@Override
					public void onClick() {
						daoCar.delete(getModelObject().getId());
						setResponsePage(ListCarPage.class);
					}
				});
			}

		});

		// redirect to the "edit" page using "empty" model to create new item as
		// result
		add(new Link<Car>("createLink", new Model<Car>(new Car())) {
			@Override
			public void onClick() {
				setResponsePage(new EditCarPage(getModelObject()));
			}
		});

	}
}
